#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@File Name: selftest.py
@Author: LTisme
@Date: 2021/8/28 15:39
@Description: ###############################################################################
              当问价作为程序运行时进行自测试文件
              ###############################################################################
"""
from .. import 邮件配置模块_mailconfig
from . import (MailFetcherConsole,                              # 从__init__中获取，因为包的话会先执行__init__.py
               MailSender, MailSenderAuthConsole,
               MailParser)

print('config:', 邮件配置模块_mailconfig.__file__)

if not 邮件配置模块_mailconfig.smtpuser:
    sender = MailSender(tracesize=5000)
else:
    sender = MailSenderAuthConsole(邮件配置模块_mailconfig.smtpservername, 邮件配置模块_mailconfig.smtpuser)

# 启动后直接开始往测试里设定的收件人发送一封邮件
sender.sendMessage(From=邮件配置模块_mailconfig.myaddress,
                   To=[邮件配置模块_mailconfig.myaddress],
                   Subj='testing mailtools package',
                   extrahdrs=[('X-Mailer', 'mailtools')],
                   bodytext='Here is my source code\n',
                   attaches=['selftest.py'],
                   )

# bodytextEncoding='utf-8',          # 其他可尝试的测试
# attachesEncodings=['latin-1'],     # 检查文本题头
# attaches=['monkeys.jpg'])          # 验证Base64 编码
# to='i18n adddr list...',           # 测试mime/unicode 题头


# 修改 邮件配置模块_mailconfig 以测试 fetchlimit
fetcher = MailFetcherConsole()


def status(*args): print(args)


# 发送完了以后，它已经一次性下载好了所有的题头，然后就会让你通过输入y来加载邮件信息，一次加载一个
hdrs, sizes, loadedall = fetcher.downloadAllHeaders(status)
for num, hdr in enumerate(hdrs[:5]):                            # 这里的切片是试验了5个
    print(hdr)
    if input('load mail?') in ['y', 'Y']:
        print(fetcher.downloadMessage(num + 1).rstrip(), '\n', '-' * 70)

# 预览完了前5个，现在开始测试后面的所有信息
last5 = len(hdrs) - 4
msgs, sizes, loadedall = fetcher.downloadAllMessages(status, loadfrom=last5)    # 载入编号从loadfrom到N的所有信息的完整信息文本
for msg in msgs:
    print(msg[:200], '\n', '-' * 70)                            # 打印的信息只有[:200]的切片，都会用 - 符号隔开看看

parser = MailParser()
for i in [0]:                       # 尝试 [0 , len(msgs)]
    fulltext = msgs[i]
    message = parser.parseMessage(fulltext)
    ctype, maintext = parser.findMainText(message)
    print('Parsed:', message['Subject'])
    print(maintext)
input('Press Enter to exit')        # 如果在windows下运行，则在此暂停
